package com.example.car

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.View.OnClickListener
import android.view.Window
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.example.car.adapter.LogoAdapter
import com.example.car.bean.LogoBean
import com.example.car.databinding.ActivityLogoBinding
import com.example.car.utils.CarApi
import com.example.car.utils.RetrofitUtils
import retrofit2.Call
import retrofit2.Response

class LogoActivity : AppCompatActivity() {
    // 获取当前ui层对象
    val binding: ActivityLogoBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_logo)
    }
    val mDatas = mutableListOf<LogoBean.ResultBean>()
    val adapter: LogoAdapter by lazy {
        LogoAdapter(this, mDatas)
    }
    var letter_msg = "当前品牌首字母:"
    var letter = "A"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val window: Window = this@LogoActivity.window
        window.statusBarColor = ContextCompat.getColor(this@LogoActivity, R.color.black)


        // 赋值ui层的变量
        binding.adapter = adapter
        binding.name = letter_msg + letter

        loadData(letter)

        binding.logoBtn.setOnClickListener(object : OnClickListener {
            // p0为当前点击的ui组件
            override fun onClick(p0: View?) {
                val lt = binding.logoEt.text.toString().trim().uppercase()
                if (!TextUtils.isEmpty(lt) && !lt.equals(letter)) {
                    letter = lt
                    binding.name = letter_msg + letter
                    loadData(letter)
                }
            }

        })

    }

    private fun loadData(letter: String) {
        val api = RetrofitUtils.getApi(CarApi.base_url, CarApi::class.java)
        val carLogo = api.getCarLogo(CarApi.key, letter)
        carLogo?.enqueue(object : retrofit2.Callback<LogoBean> {
            override fun onResponse(call: Call<LogoBean>, response: Response<LogoBean>) {
                val bean: LogoBean? = response.body()
                mDatas.clear()
                adapter.addDatas(bean?.getResult())
            }

            override fun onFailure(call: Call<LogoBean>, t: Throwable) {
            }

        })
    }
}